import plugin from '../../lib/plugins/plugin.js'
import common from "../../lib/common/common.js";
import YAML from "yaml"
import path from "path";
import fs from "fs"

let fukpath = 'resources/zhao';
if (!fs.existsSync(fukpath)) {
    fs.mkdirSync(fukpath);
}
let wei = ['逼','色','操','杀','卵','杂种']  
let cdtime = 10; //cd时间，单位秒
let cooldowns = new Map();
export class example extends plugin {
    constructor() {
        super({
            name: "召唤群友",
            dsc: "召唤群友",
            event: "message",
            priority: 1000, //指令优先级
            rule: [
			{
                reg: '^#?(设置|新增)(召唤|呼叫|传唤)(.*)$', 
                fnc: "setzhao",
            },
			{
                reg: '^#?(删除|移除)(召唤|呼叫|传唤)(列表)?(.*)$', 
                fnc: "delzhao",
            },
			{
                reg: '^#?(查看|查询)(召唤|呼叫|传唤)列表(.*)$', 
                fnc: "chazhao",
            },
			{
                reg: '^#?(召唤|呼叫|传唤)(.*)$',
                fnc: "zhao",
            },
           ]
        });
    }


async setzhao(e) {
    if (e.isGroup) {
        let key = e.msg.replace(/#|(设置|新增)(召唤|呼叫|传唤)/g, '').trim();
        if (e.at && key) {
            if (wei.some(w => key.includes(w))) {
                logger.info(`检测到关键词不予添加`);
                return;
            }

            let id = e.at;
            let dem = `${fukpath}/${e.group_id}.json`;

            if (!fs.existsSync(dem)) {
                fs.writeFileSync(dem, JSON.stringify({}));
            }

            let demData = JSON.parse(fs.readFileSync(dem, 'utf8'));
            if (!Array.isArray(demData[key])) {
                demData[key] = [];
            }

            if (!demData[key].includes(id)) {
                demData[key].push(id); 
                fs.writeFileSync(dem, JSON.stringify(demData, null, 2)); 
                e.reply(`${id} 已成功添加到召唤列表 ${key}`);
            } else {
                e.reply(`${id} 已存在召唤列表 ${key}`);
            }

            return true;
        }
    }
}
  
async delzhao(e) {
    if (e.isGroup) {
        let key = e.msg.replace(/#|(移除|删除)(召唤|呼叫|传唤)(列表)?/g, '').trim();
        if (key) {
            let dem = `${fukpath}/${e.group_id}.json`;
            if (!fs.existsSync(dem)) {

                return;
            }

            let demData = JSON.parse(fs.readFileSync(dem, 'utf8'));

            if ((/#?(移除|删除)(召唤|呼叫|传唤)列表/).test(e.msg)) {
                if (demData[key]) {
                    delete demData[key]; // 删除整个 key
                    fs.writeFileSync(dem, JSON.stringify(demData, null, 2)); // 保存文件
                    e.reply(`召唤列表 ${key} 已被移除`);
                } else {
                    e.reply(`召唤列表 ${key} 不存在`);
                }
                return true;
            }

            if (e.at) {
                let id = e.at;
                if (!Array.isArray(demData[key])) {
                    e.reply(`召唤列表 ${key} 不存在或为空`);
                    return;
                }

                let index = demData[key].indexOf(id);
                if (index !== -1) {
                    demData[key].splice(index, 1); 
                    fs.writeFileSync(dem, JSON.stringify(demData, null, 2)); 
                    e.reply(`${id} 已从召唤列表 ${key} 中移除`);
                } else {
                    e.reply(`${id} 不存在于召唤列表 ${key}`);
                }
                return true;
            }

            e.reply(`未检测到需要移除的目标`);
        }
    }
}
  
async chazhao(e) {
	if (e.isGroup) {
		let key = e.msg.replace(/#|(查看|查询)(召唤|呼叫|传唤)列表/g, '').trim();
		    let dem = `${fukpath}/${e.group_id}.json`;
            if (!fs.existsSync(dem)) {

                return;
            }

            let demData = JSON.parse(fs.readFileSync(dem, 'utf8'));
		if (!key) {
            let allLists = [];
            for (let listKey in demData) {
                if (Array.isArray(demData[listKey]) && demData[listKey].length > 0) {
                    allLists.push(`召唤列表 ${listKey} 下的 QQ：\n${demData[listKey].join('\n')}`);
                }
            }
            if (allLists.length > 0) {
                e.reply(await common.makeForwardMsg(e, allLists));
            } 
            return;
        }
			
            if (!Array.isArray(demData[key])) {

                return;
            }
		    let qqList = demData[key];
            if (qqList.length > 0) {
                e.reply(`召唤列表 ${key} 下的 QQ：\n${qqList.join('\n')}`);
            }
	}
}
  
async zhao(e) {
	if (e.isGroup) {
		let key = e.msg.replace(/#|(召唤|呼叫|传唤)/g, '').trim();
		let dem = `${fukpath}/${e.group_id}.json`;
        if (!fs.existsSync(dem)) {

            return;
        }

        let demData = JSON.parse(fs.readFileSync(dem, 'utf8'));
        if (!Array.isArray(demData[key])) {

            return;
        }
	if (!e.isMaster) {	
	    const userId = e.user_id;
        const cooldown = cooldowns[userId];
        if (cooldown && cooldown > Date.now()) {
            const remainingTime = Math.ceil((cooldown - Date.now()) / 1000);
            e.reply("指令冷却中还有" + remainingTime + "秒~");
            return;
        }
        cooldowns[userId] = Date.now() + cdtime * 1000;
	}
        let msgs = []
		let qqList = demData[key];
        if (qqList.length > 0) {
            for (let qq of qqList) {
				   msgs.push(segment.at(qq))
			    }
            }
		msgs.push(`\n${key}${qqList.length > 1 ? '们' : ''}快出来接客了！`)
	    e.reply(msgs)
	    }
	}

}